package com.itheima.reggie.controller;



import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("common")
@Slf4j
public class CommonController {

    @Value("${reggin.path}")
    private String BasePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        log.info(file.toString());
        //原始文件名
        String filename = file.getOriginalFilename();
        String s = filename.substring(filename.lastIndexOf("."));
        //使用UUID生成新的文件名称
        String s1 = UUID.randomUUID().toString() + s;
        //创建目录对象
        File file1 = new File(BasePath);
        //判断目录是否存在
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //将文件转存到指定的位置
        file.transferTo(new File(BasePath + s1));
        return R.success(s1);
    }

    /**
     * 文件下载
     */
    @GetMapping("download")
    public void download(HttpServletResponse response,String name) {
        try {
            //输入流，通过输入流读取内容
            FileInputStream fileInputStream = new FileInputStream(new File(BasePath + name));
            //输出流，通过输出流将文件传回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //设置响应数据格式
            response.setContentType("");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len=fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
